Popular Searches
Popular Course Categories
Popular Courses

Working with Single and Multilevel Inheritance

Working with Single and Multilevel Inheritance

Encapsulation, Inheritance, and Polymorphism

Working with Single and Multilevel Inheritance in Java

Course: Core Java Training

Topic: Working with Single and Multilevel Inheritance

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Inheritance in Java

Inheritance is one of the four fundamental principles of Object-Oriented Programming (OOP). It allows one class to acquire accessible fields and methods from another class. Inheritance supports code reuse, improves program organization, and helps developers represent relationships between related classes.

In Java, the class that provides inherited functionality is called the parent class, superclass, or base class. The class that inherits from it is called the child class, subclass, or derived class.

Java uses the extends keyword to establish inheritance between classes. A subclass can use accessible inherited methods, define its own methods and fields, and override eligible inherited instance methods to provide specialized behavior.

Example of Inheritance

class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();

        dog.eat();
        dog.bark();
    }
}

Output:

Animal is eating.
Dog is barking.

Here, Dog inherits the accessible eat() method from Animal and defines its own bark() method. The Dog object can call both methods.

2. What Is Single Inheritance?

Single inheritance occurs when one subclass directly extends one superclass. It establishes a direct parent-child relationship between two classes.

For example, a Car class can inherit common properties and methods from a Vehicle class. The vehicle class can provide shared behavior, while the car class adds functionality specific to cars.

Structure of Single Inheritance

        Vehicle
           |
           v
          Car

In this structure, Vehicle is the superclass and Car is the subclass.

Syntax

class Parent {
    // Fields and methods
}

class Child extends Parent {
    // Additional fields and methods
}

3. Complete Example of Single Inheritance

The following example demonstrates how a child class can reuse the methods of its parent class while adding its own behavior.

class Vehicle {
    String brand = "Toyota";

    void start() {
        System.out.println("Vehicle is starting.");
    }

    void stop() {
        System.out.println("Vehicle is stopping.");
    }
}

class Car extends Vehicle {
    int numberOfDoors = 4;

    void displayDetails() {
        System.out.println("Brand: " + brand);
        System.out.println("Number of Doors: " + numberOfDoors);
    }
}

public class SingleInheritanceDemo {
    public static void main(String[] args) {
        Car car = new Car();

        car.start();
        car.displayDetails();
        car.stop();
    }
}

Output:

Vehicle is starting.
Brand: Toyota
Number of Doors: 4
Vehicle is stopping.

Explanation

  • Vehicle is the parent class.
  • Car extends Vehicle and is the child class.
  • The start() and stop() methods are inherited from Vehicle.
  • The numberOfDoors field and displayDetails() method belong to Car.
  • The Car object can access the inherited public or otherwise accessible members along with its own members.

This approach avoids rewriting common vehicle operations in every vehicle-related class.

4. Real-World Applications of Single Inheritance

Single inheritance is useful when one class represents a specialized form of another class.

Parent Class Child Class Possible Inherited Behavior
Employee Manager Employee ID, name, and common employee operations.
Vehicle Car Starting, stopping, and shared vehicle information.
Animal Dog Common animal behavior such as eating.
Account SavingsAccount Shared account information and applicable operations.
Product ElectronicProduct Common product details and product-related methods.

Inheritance should represent a meaningful is-a relationship. For example, a car is a vehicle. If two classes are unrelated or one merely uses another, composition may be a better design choice.

5. What Is Multilevel Inheritance?

Multilevel inheritance occurs when a class inherits from another subclass, forming a chain of inheritance across three or more levels.

For example, a LivingThing class can be extended by an Animal class, and then a Dog class can extend Animal. In this hierarchy, Dog indirectly inherits accessible members from LivingThing through Animal.

Structure of Multilevel Inheritance

       LivingThing
            |
            v
          Animal
            |
            v
            Dog

In this hierarchy:

  • LivingThing is the top-level superclass.
  • Animal directly extends LivingThing.
  • Dog directly extends Animal.
  • Dog can access eligible inherited members from both earlier levels.

Syntax

class A {
    // Common behavior
}

class B extends A {
    // Additional behavior
}

class C extends B {
    // More specialized behavior
}

6. Complete Example of Multilevel Inheritance

The following example demonstrates a three-level inheritance hierarchy.

class LivingThing {
    void breathe() {
        System.out.println("Living things breathe.");
    }
}

class Animal extends LivingThing {
    void eat() {
        System.out.println("Animals need food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dogs can bark.");
    }
}

public class MultilevelInheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();

        dog.breathe();
        dog.eat();
        dog.bark();
    }
}

Output:

Living things breathe.
Animals need food.
Dogs can bark.

Explanation

  • LivingThing defines the breathe() method.
  • Animal extends LivingThing and adds the eat() method.
  • Dog extends Animal and adds the bark() method.
  • A Dog object can call breathe(), eat(), and bark() because these methods are accessible in the inheritance hierarchy.

Multilevel inheritance helps organize functionality from general behavior to increasingly specialized behavior.

7. Practical Example: Employee and Manager Hierarchy

A company may have a general employee class, a full-time employee class, and a manager class. Each level can add relevant information while reusing suitable functionality from the previous level.

class Employee {
    String name;
    int employeeId;

    Employee(String name, int employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }

    void displayEmployee() {
        System.out.println("Name: " + name);
        System.out.println("Employee ID: " + employeeId);
    }
}

class FullTimeEmployee extends Employee {
    double monthlySalary;

    FullTimeEmployee(String name, int employeeId, double monthlySalary) {
        super(name, employeeId);
        this.monthlySalary = monthlySalary;
    }

    void displaySalary() {
        System.out.println("Monthly Salary: " + monthlySalary);
    }
}

class Manager extends FullTimeEmployee {
    String department;

    Manager(String name, int employeeId, double monthlySalary,
            String department) {
        super(name, employeeId, monthlySalary);
        this.department = department;
    }

    void displayManagerDetails() {
        displayEmployee();
        displaySalary();
        System.out.println("Department: " + department);
    }
}

public class EmployeeHierarchyDemo {
    public static void main(String[] args) {
        Manager manager = new Manager(
            "Riya", 101, 65000.00, "Technology"
        );

        manager.displayManagerDetails();
    }
}

Output:

Name: Riya
Employee ID: 101
Monthly Salary: 65000.0
Department: Technology

Important Concepts in This Example

  • Employee stores common employee details.
  • FullTimeEmployee adds salary-related information.
  • Manager adds a department field and a method for displaying manager details.
  • The super() call invokes the appropriate constructor of the direct superclass.
  • Each class reuses existing behavior rather than duplicating the same implementation.

8. Understanding the super Keyword

The super keyword refers to the superclass portion of the current object. It is commonly used to call a superclass constructor, invoke an inherited method implementation, or access a superclass field when a subclass declaration hides a field with the same name.

8.1 Calling a Parent Constructor

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    int rollNumber;

    Student(String name, int rollNumber) {
        super(name);
        this.rollNumber = rollNumber;
    }
}

The statement super(name) calls the matching constructor in Person to initialize the inherited name information.

8.2 Calling a Parent Method

class Parent {
    void display() {
        System.out.println("Parent method.");
    }
}

class Child extends Parent {
    @Override
    void display() {
        super.display();
        System.out.println("Child method.");
    }
}

Here, super.display() invokes the superclass implementation before the child class prints its own message.

9. Constructor Execution in Inheritance

Constructors are not inherited like ordinary methods. When a subclass object is created, Java initializes the superclass portion of the object as part of the construction process.

A superclass constructor can be invoked using super(...). If no constructor invocation is explicitly written, Java may insert an implicit no-argument superclass constructor invocation when the language rules allow it. If the superclass has no accessible no-argument constructor, the subclass must invoke an appropriate superclass constructor explicitly.

Example

class A {
    A() {
        System.out.println("Constructor of A");
    }
}

class B extends A {
    B() {
        System.out.println("Constructor of B");
    }
}

class C extends B {
    C() {
        System.out.println("Constructor of C");
    }
}

public class ConstructorChainDemo {
    public static void main(String[] args) {
        C obj = new C();
    }
}

Output:

Constructor of A
Constructor of B
Constructor of C

The superclass constructor chain runs before the corresponding subclass constructor bodies. This allows each level to initialize its own part of the object.

10. Method Overriding in Inheritance

Method overriding occurs when a subclass provides its own implementation of an eligible instance method inherited from a superclass, using a compatible method signature and return type. It allows a subclass to specialize behavior while keeping the same method interface.

Example

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound.");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks.");
    }
}

public class MethodOverridingDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.makeSound();
    }
}

Output:

Dog barks.

The Dog class overrides makeSound(), so the implementation provided by Dog runs when the method is invoked on a Dog object.

Note: Constructors, private methods, and static methods do not participate in instance-method overriding in the same way as eligible inherited instance methods. Static methods can be hidden, while private methods are not inherited as accessible methods by subclasses.

11. Single Inheritance vs. Multilevel Inheritance

Basis Single Inheritance Multilevel Inheritance
Structure One subclass directly extends one superclass. A chain of inheritance extends across multiple levels.
Number of levels Usually two classes in the basic relationship. Three or more classes in the hierarchy.
Example Vehicle → Car LivingThing → Animal → Dog
Code reuse Reuses members from the direct parent. Can reuse eligible members from several ancestor levels.
Complexity Generally simpler to understand. Can be more complex as the hierarchy grows.
Best suited for A straightforward parent-child relationship. Progressive specialization across related types.

12. Advantages of Inheritance

  • Code reusability: Common methods can be defined once in a superclass.
  • Reduced duplication: Subclasses can reuse suitable existing implementations.
  • Clear relationships: Inheritance can represent meaningful is-a relationships.
  • Extensibility: Subclasses can add specialized fields and methods.
  • Polymorphism: A superclass reference can refer to a subclass object, allowing overridden methods to be selected at runtime.
  • Easier maintenance: Shared behavior can be maintained in a common superclass when the hierarchy is designed appropriately.

13. Limitations and Potential Problems

  • Tight coupling: A subclass depends on aspects of its superclass, so changes to the superclass may affect subclasses.
  • Deep hierarchies: Long inheritance chains can make behavior harder to trace.
  • Incorrect relationships: Inheritance is unsuitable when the child does not represent a genuine specialized form of the parent.
  • Overridden behavior: Subclasses can change inherited behavior in ways that surprise callers if the design contract is unclear.
  • Restricted class inheritance: A Java class can directly extend only one class.

Use inheritance when there is a meaningful is-a relationship. If a class simply needs to use the functionality of another class, consider composition instead.

14. Common Mistakes to Avoid

Mistake Explanation Solution
Forgetting extends The intended inheritance relationship is not declared. Use class Child extends Parent.
Calling a private parent field directly Private fields are not directly accessible to subclasses. Use an appropriate superclass method or redesign the access interface.
Using super() incorrectly The selected constructor may not exist or may not be accessible. Call a valid superclass constructor with matching arguments.
Confusing inheritance with object creation Declaring extends does not create a separate parent object that can be used independently. Understand that the subclass object includes the superclass portion of its state.
Building excessively deep hierarchies Behavior and dependencies become harder to understand. Keep hierarchies meaningful and prefer composition when appropriate.
Overriding without considering the parent contract Changed behavior may break expectations of callers. Follow the superclass method's documented behavior and use @Override.

15. Troubleshooting Inheritance Errors

Problem 1: Cannot Find Symbol

Cause: A method name may be misspelled, the method may not exist in the parent class, or the member may not be accessible.

Solution: Check the method declaration, spelling, access modifier, and inheritance relationship.

Problem 2: Constructor Cannot Be Applied to Given Types

Cause: The subclass calls a superclass constructor with incorrect arguments or relies on a no-argument constructor that does not exist.

Solution: Check the available superclass constructors and use a matching super(...) call.

Problem 3: Non-Static Method Cannot Be Referenced from a Static Context

Cause: An instance method is called directly from a static method without an object reference.

Solution: Create an appropriate object or use an object reference to call the instance method.

Problem 4: Attempting to Extend a Final Class

Cause: A class declared with final cannot be subclassed.

Solution: If the class is under your control and extension is appropriate, review whether final is required. Otherwise, use the class through its public API or composition.

16. Practical Exercises

  1. Vehicle and Car: Create a Vehicle class with start() and stop() methods. Extend it with a Car class that displays the car's brand.
  2. Person and Student: Create a Person class with a name field and a Student subclass with a roll number.
  3. Animal hierarchy: Create Animal, Mammal, and Dog classes to demonstrate multilevel inheritance.
  4. Employee hierarchy: Create Employee, FullTimeEmployee, and Manager classes. Add suitable constructors and display methods.
  5. Method overriding: Define a makeSound() method in Animal and override it in Dog and Cat.
  6. Constructor chain: Create three classes in an inheritance chain and print a message from each constructor to observe execution order.

17. Mini Project: Employee Management Hierarchy

Objective: Build a simple employee management program using single and multilevel inheritance.

Project Requirements

  • Create an Employee superclass with employee name and ID.
  • Create a Developer subclass that adds a programming language.
  • Create a SeniorDeveloper subclass that extends Developer and adds a mentoring responsibility.
  • Use constructors to initialize each class's information.
  • Use super() to initialize superclass fields.
  • Define display methods to show information from each level.
  • Override a method if a subclass needs specialized behavior.

Expected Learning Outcomes

After completing this project, learners should be able to create inheritance hierarchies, reuse inherited behavior, initialize objects using constructor chaining, and understand how subclasses extend or override superclass functionality.

18. Core Java Interview Questions and Answers

Q1. What is inheritance in Java?

Answer: Inheritance is an OOP mechanism through which a class extends another class and acquires its accessible members, allowing reuse and specialization of behavior.

Q2. What is single inheritance?

Answer: Single inheritance occurs when one subclass directly extends one superclass.

Q3. What is multilevel inheritance?

Answer: Multilevel inheritance is a chain in which a class extends a subclass that itself extends another class, such as A → B → C.

Q4. Which keyword is used for class inheritance in Java?

Answer: The extends keyword is used when one class inherits from another class.

Q5. Can Java support multilevel inheritance?

Answer: Yes. A class can extend another class that itself extends a superclass, creating multiple inheritance levels.

Q6. Does a subclass inherit private members?

Answer: Private members are part of the superclass's implementation, but they are not directly accessible by the subclass. The subclass may interact with the superclass state through accessible methods provided by the superclass.

Q7. What is the purpose of the super keyword?

Answer: The super keyword is used to invoke a superclass constructor, call a superclass method implementation, or refer to a superclass field hidden by a subclass field.

Q8. Are constructors inherited in Java?

Answer: No. Constructors are not inherited. A subclass constructor can invoke a superclass constructor as part of initializing the object.

Q9. What is method overriding?

Answer: Method overriding occurs when a subclass provides a compatible implementation of an eligible inherited instance method, enabling specialized behavior.

Q10. Can a Java class extend two classes directly?

Answer: No. A Java class can directly extend only one class. Java supports multiple inheritance of type through interfaces, subject to interface rules.

Q11. What is the difference between single and multilevel inheritance?

Answer: Single inheritance involves one direct superclass-subclass relationship, while multilevel inheritance involves a chain of inheritance across multiple classes.

Q12. When should inheritance be avoided?

Answer: Avoid inheritance when there is no meaningful is-a relationship, when it creates excessive coupling, or when composition offers a simpler and more flexible design.

19. Quick Revision Checklist

  • Understand the role of a superclass and a subclass.
  • Use extends to declare class inheritance.
  • Recognize single inheritance as one direct parent-child relationship.
  • Recognize multilevel inheritance as a chain of classes.
  • Know which inherited members are accessible from a subclass.
  • Use super() to invoke an appropriate superclass constructor.
  • Remember that constructors are not inherited.
  • Use @Override when overriding an inherited instance method.
  • Prefer meaningful is-a relationships and avoid unnecessarily deep hierarchies.
  • Use composition when a class needs another object rather than being a specialized form of it.

20. Conclusion

Single and multilevel inheritance are important concepts in Core Java that help organize related classes and reuse common functionality. Single inheritance creates a direct relationship between a parent and child class, while multilevel inheritance creates a chain of increasingly specialized classes.

By understanding the extends and super keywords, constructor execution, access modifiers, and method overriding, developers can build clear and reusable object-oriented programs. Practice with examples such as vehicles, animals, students, and employees to strengthen your understanding of inheritance.

Continue Learning with JustAcademy

Explore the Core Java Training Course to continue learning Java fundamentals, object-oriented programming, classes, objects, inheritance, polymorphism, and practical application development.

Register for a Course Demo to learn more about the training, or visit the JustAcademy website.

Previous Next
whatsapp